//
//  ExplainActionRequestHandler.m
//  ActionExtensionSample
//
//  Created by 冯鸿杰 on 2017/6/5.
//  Copyright © 2017年 Mob. All rights reserved.
//

#import "ExplainActionRequestHandler.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import <UIKit/UIKit.h>

@implementation ExplainActionRequestHandler

- (void)beginRequestWithExtensionContext:(NSExtensionContext *)context
{
    __weak typeof(self) weakSelf = self;
    NSExtensionItem *item = context.inputItems.firstObject;
    NSItemProvider *itemProvider = item.attachments.firstObject;
    if ([itemProvider hasItemConformingToTypeIdentifier:(NSString *)kUTTypePropertyList])
    {
        [itemProvider loadItemForTypeIdentifier:(NSString *)kUTTypePropertyList
                                        options:nil
                              completionHandler:^(id<NSSecureCoding>  _Nullable item, NSError * _Null_unspecified error) {
                                  
                                  NSDictionary *jsData = item[NSExtensionJavaScriptPreprocessingResultsKey];
                                  NSString *text = jsData[@"text"];
                                  
                                  if (text)
                                  {
                                      //进行文本解释
                                      [weakSelf resultExplainWithData:@{@"explain" : @"问我之前请先百度一下", @"text" : text} context:context];
                                  }
                                  else
                                  {
                                      [context completeRequestReturningItems:nil completionHandler:nil];
                                  }
                                  
                              }];
    }
}

- (void)resultExplainWithData:(NSDictionary *)data context:(NSExtensionContext *)context
{
    NSDictionary *resultsDictionary = @{ NSExtensionJavaScriptFinalizeArgumentKey: data };
    
    NSItemProvider *resultsProvider = [[NSItemProvider alloc] initWithItem:resultsDictionary typeIdentifier:(NSString *)kUTTypePropertyList];
    
    NSExtensionItem *resultsItem = [[NSExtensionItem alloc] init];
    resultsItem.attachments = @[resultsProvider];
    
    // Signal that we're complete, returning our results.
    [context completeRequestReturningItems:@[resultsItem] completionHandler:nil];
}

@end
